<?php
/**
 * User: hjd-yao
 * Date: 2019/6/17
 * Time: 14:38
 */

namespace App\Models\User;


use App\Helpers\SelfEncrypt;
use App\Models\BaseModel;
use DC\UserCenter\Models\UserWalletModel;
use Frontend\Models\UserBaseModel;

class WdModel extends BaseModel
{
    protected $table = 'user_wd';

    protected $primaryKey = 'id';

    public $dateFormat = 'U';

    protected $dates = [
        'created_at',
        'updated_at',
        'handled_at',
    ];

    private static $accountType = [
        3=>"银行卡",
        2=>"微信",
        1=>"支付宝",
    ];

    public function user()
    {
        return $this->belongsTo('DC\UserCenter\Models\UserBaseModel','user_id','member_id');
    }

    public function apply($data)
    {
        $user_id = request()->input('user_id');
        $money = $data['money'];
        $user = UserBaseModel::find($user_id);
        if(!$user){
            $this->errorMsg = '会员信息不存在';
            return false;
        }

        $account_type =$data['pay_type'];
        $account = $this->handleAccount($user,$account_type);
        if(!$account){
            return false;
        }

        $service_fee = 0 ;
        if(get_rule('wd_tax') >0 && get_rule('wd_tax') <100){
            $service_fee =  $money * get_rule('wd_tax') * 0.01;
        }

        $this->wd_sn = SelfEncrypt::createCode('WD');
        $this->user_id = $user_id;
        $this->service_fee = $service_fee;
        $this->money = $money-$service_fee;
        $this->to_account = json_encode($account);
        $this->to_phone = $user->user_phone;
        $this->apply_remark = $data['remark'];

        if(!UserWalletModel::where('member_id',$user_id)->decrement('money2',$money)){
            return false;
        }
        $params = [
            'money_type'=>2,
            'change_type'=>51,
            'before_money'=>$user->wallet->money2,
        ];
        AccountFlowModel::init()->createFlow($user_id,$money,0,$params);
        return $this->save();
    }

    private function handleAccount($user,$account_type)
    {
        $account = [
            "类型"=>self::$accountType[$account_type]
        ];
        if($account_type == 1){
            if(!$user->info->alipay){
                $this->errorMsg = '支付宝信息不存在';
                return false;
            }
            $account["账号"] = $user->info->alipay;
        }elseif ($account_type == 2){
            if(!$user->info->weichat){
                $this->errorMsg = '微信信息不存在';
                return false;
            }
            $account["账号"] = $user->info->weichat;
        }else{
            if(!$user->info->bank_card){
                $this->errorMsg = '银行卡信息不存在';
                return false;
            }
            $account["账号"] = $user->info->bank_card;
            $account["开户行"] = $user->info->bank_name;
        }
        return $account;
    }
}